package com.daykw.ip.task;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.springframework.stereotype.Service;

import com.daykw.ip.model.Ips;
import com.daykw.ip.task.thread.CheckProxyIpThread;
import com.daykw.ip.util.Const;
import com.daykw.ip.util.SpringContextHolder;

@Service
public class CheckIpTask extends CustmTask {
	private static Logger logger = Logger.getLogger(CheckIpTask.class);

	@Override
	public void doStart() {

		try {
			/**
			 * 5分钟切换一次ip
			 */

			if (QuartzManager.getTrigger("CheckIpTask") == null) {
				QuartzManager.addJob("CheckIpTask", this, "0 0/1 * * * ?");
			} else {
				logger.error("############已经存在任务：CleanIpTask############");
			}
		} catch (Exception e) {
			logger.error("", e);
		}

	}//

	@Override
	public void doWork() {
		try {
			if (SpringContextHolder.getApplicationContext() == null) {
				try {
					TimeUnit.SECONDS.sleep(3);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				logger.info("等待上下文启动");
			}
			//NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			NutDao bdsDao = SpringContextHolder.getBean("bdsDao");
			DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String nowtime = FORMAT.format(new Date());

			String querySql = "SELECT * FROM t_ips WHERE id >= ((SELECT MAX(id) FROM t_ips)-(SELECT MIN(id) FROM t_ips)) * RAND() + (SELECT MIN(id) FROM t_ips)  LIMIT 1000";

			Sql sql = Sqls.queryEntity(querySql);
			sql.setCallback(Sqls.callback.entities());
//			sql.setEntity(xhsDao.getEntity(Ips.class));
//			xhsDao.execute(sql);
//			List<Ips> xhslist = sql.getList(Ips.class);

			sql.setEntity(bdsDao.getEntity(Ips.class));
			bdsDao.execute(sql);
			List<Ips> bdslist = sql.getList(Ips.class);
			ExecutorService pool = Const.getKeyThreadPool(1000);
//			for (int i = 0; i < xhslist.size(); i++) {
//				Ips ip = xhslist.get(i);
//				CheckProxyIpThread ips = new CheckProxyIpThread(ip, xhsDao);
//				pool.execute(ips);
//			}

			for (int i = 0; i < bdslist.size(); i++) {
				Ips ip = bdslist.get(i);
				CheckProxyIpThread ips = new CheckProxyIpThread(ip, bdsDao);
				pool.execute(ips);
			}

		} catch (Exception e) {
			logger.error("", e);
		}
	}

}
